package com.vegetable.modules.controller.sys;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.vegetable.common.utils.EntityDiffUtils;
import com.vegetable.common.utils.R;
import com.vegetable.modules.entity.sys.SysLogEntity;
import com.vegetable.modules.entity.sys.po.EntityChangeLogQueryPO;
import com.vegetable.modules.service.sys.SysLogService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

/**
 * 实体变更日志Controller
 */
@RestController
@RequestMapping("/sys/entityChangeLog")
@Api(value = "实体变更日志", tags = "实体变更日志")
public class EntityChangeLogController {
    
    @Autowired
    private SysLogService sysLogService;
    
    /**
     * 分页查询实体变更日志
     */
    @GetMapping("/list")
    @ApiOperation(value = "分页查询实体变更日志", notes = "分页查询实体变更日志")
    public R list(EntityChangeLogQueryPO po) {
        Page<SysLogEntity> page = new Page<>(po.getPage(), po.getLimit());
        
        QueryWrapper<SysLogEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.isNotNull("entity_class");
        queryWrapper.orderByDesc("create_date");
        
        // 根据实体类名筛选
        if (po.getEntityClass() != null && !po.getEntityClass().isEmpty()) {
            queryWrapper.like("entity_class", po.getEntityClass());
        }
        
        // 根据操作类型筛选
        if (po.getOperationType() != null && !po.getOperationType().isEmpty()) {
            queryWrapper.eq("operation_type", po.getOperationType());
        }
        
        // 根据用户名筛选
        if (po.getUsername() != null && !po.getUsername().isEmpty()) {
            queryWrapper.like("username", po.getUsername());
        }
        
        page = sysLogService.page(page, queryWrapper);
        
        // 为每条记录生成字段变更详情
        page.getRecords().forEach(record -> {
            if (record.getBeforeData() != null || record.getAfterData() != null) {
                // 生成标准字段变更详情
                record.setFieldChanges(EntityDiffUtils.generateFieldChanges(record.getBeforeData(), record.getAfterData()));
                
                // 尝试生成详细字段变更信息（包含字段描述）
                try {
                    // 通过反射获取实体类
                    if (record.getEntityClass() != null && !record.getEntityClass().isEmpty()) {
                        Class<?> entityClass = Class.forName(record.getEntityClass());
                        Object beforeObj = null;
                        Object afterObj = null;
                        
                        if (record.getBeforeData() != null && !record.getBeforeData().isEmpty()) {
                            beforeObj = EntityDiffUtils.getObjectMapper().readValue(record.getBeforeData(), entityClass);
                        }
                        
                        if (record.getAfterData() != null && !record.getAfterData().isEmpty()) {
                            afterObj = EntityDiffUtils.getObjectMapper().readValue(record.getAfterData(), entityClass);
                        }
                        
                        List<Map<String, Object>> detailedChanges = EntityDiffUtils.compareObjectsWithDescriptions(beforeObj, afterObj);
                        record.setDetailedFieldChanges(detailedChanges);
                        
                        // 打印调试信息
                        System.out.println("实体类: " + record.getEntityClass());
                        System.out.println("BeforeData: " + record.getBeforeData());
                        System.out.println("AfterData: " + record.getAfterData());
                        System.out.println("详细变更数量: " + (detailedChanges != null ? detailedChanges.size() : 0));
                        if (detailedChanges != null) {
                            for (Map<String, Object> change : detailedChanges) {
                                System.out.println("字段: " + change.get("fieldName") + 
                                                 ", 描述: " + change.get("fieldDescription") + 
                                                 ", 旧值: " + change.get("oldValue") + 
                                                 ", 新值: " + change.get("newValue"));
                            }
                        }
                    }
                } catch (Exception e) {
                    // 忽略异常，保持原有功能
                    e.printStackTrace();
                }
            }
        });
        
        return R.data(page);
    }
    
    /**
     * 获取实体变更详情
     */
    @GetMapping("/info")
    @ApiOperation(value = "获取实体变更详情", notes = "获取实体变更详情")
    public R info(Long id) {
        SysLogEntity logEntity = sysLogService.getById(id);
        if (logEntity == null) {
            // 先检查是否存在该ID的任何记录
            QueryWrapper<SysLogEntity> wrapper = new QueryWrapper<>();
            wrapper.eq("id", id);
            SysLogEntity anyEntity = sysLogService.getOne(wrapper);
            
            if (anyEntity != null) {
                return R.fail(400, "找到了记录，但不是实体变更日志记录");
            }
            return R.fail(400, "未找到指定的日志记录");
        }
        
        // 检查是否为实体变更日志
        if (logEntity.getEntityClass() == null) {
            return R.fail(400, "找到的记录不是实体变更日志记录");
        }
        
        // 生成字段变更详情
        if (logEntity.getBeforeData() != null || logEntity.getAfterData() != null) {
            // 生成标准字段变更详情
            logEntity.setFieldChanges(EntityDiffUtils.generateFieldChanges(logEntity.getBeforeData(), logEntity.getAfterData()));
            
            // 生成详细字段变更信息（包含字段描述）
            try {
                // 通过反射获取实体类
                if (logEntity.getEntityClass() != null && !logEntity.getEntityClass().isEmpty()) {
                    Class<?> entityClass = Class.forName(logEntity.getEntityClass());
                    Object beforeObj = null;
                    Object afterObj = null;
                    
                    if (logEntity.getBeforeData() != null && !logEntity.getBeforeData().isEmpty()) {
                        beforeObj = EntityDiffUtils.getObjectMapper().readValue(logEntity.getBeforeData(), entityClass);
                    }
                    
                    if (logEntity.getAfterData() != null && !logEntity.getAfterData().isEmpty()) {
                        afterObj = EntityDiffUtils.getObjectMapper().readValue(logEntity.getAfterData(), entityClass);
                    }
                    
                    logEntity.setDetailedFieldChanges(EntityDiffUtils.compareObjectsWithDescriptions(beforeObj, afterObj));
                }
            } catch (Exception e) {
                // 忽略异常，保持原有功能
                e.printStackTrace();
            }
        }
        
        return R.data(logEntity);
    }
    
    /**
     * 检查是否存在实体变更日志记录
     */
    @GetMapping("/check")
    @ApiOperation(value = "检查是否存在实体变更日志记录", notes = "检查是否存在实体变更日志记录")
    public R check() {
        QueryWrapper<SysLogEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.isNotNull("entity_class");
        queryWrapper.orderByDesc("create_date");
        queryWrapper.last("LIMIT 1");
        
        SysLogEntity logEntity = sysLogService.getOne(queryWrapper);
        if (logEntity == null) {
            return R.fail(400, "系统中暂无实体变更日志记录，请先进行一些实体操作");
        }
        
        return R.data("系统中存在实体变更日志记录");
    }
}